/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Connections;

import Entities.Config;
import Business.ConfigManage;
import java.sql.*;


/**
 *
 * @author Nhit
 */
public class Database {

    private Connection conn = null;
    //
    private String classDriver;

    /*
     * Default constructor to register the JDBC Driver (MS SQL Server 2005 is default)
     * @param: no parameter.
     * @return: object of this class.
     */
    public Database() {
        this.classDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    }

    /*
     * The other constructor used when you need to work with another software database management
     * @param: String Driver the string to get class for driver of the software database management
     * @return: object of this class.
     */
    public Database(String Driver) throws Exception {
        this.classDriver = Driver;
    }

    /**
     * This static method is used to get a SQL Server Connection String from file connection.properties
     * @return  the SQL Server Connection String from file configuration.properties
     **/
   
    public String getConnectionUrl(){
        ConfigManage objConfigManage= new ConfigManage();
        Config objConfig = objConfigManage.getConfigProperties();
        return "jdbc:sqlserver://" + objConfig.getServerName() + ":" + objConfig.getPortNumber()
                    +  ";databaseName=" + objConfig.getDatabase()
                    + ";User=" + objConfig.getUserName() + ";Password=" + objConfig.getPassword();
    }
   /*
    *  This method is used to optain a connection to database
    */
    public Connection getConn() {
        try {
            Class.forName(this.classDriver);
            System.out.println("Load driver succ !");
            conn = DriverManager.getConnection(getConnectionUrl());
        } catch (SQLException ex) {
            System.out.println("Connect error 2!");
           // Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            System.out.println("Load driver error");
            //Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex){
            System.out.println("Connect failt");
        }
        return conn;
    }

    /*
     * This method is used to close connection
     */
    public void closeConn() {
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (SQLException ex) {
                System.out.println("close connection error");
               // Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}
